//
//  UITextField+HBTextLength.m
//  HBLibary
//
//  Created by Rambo on 2018/6/8.
//

#import "UITextField+HBTextLength.h"
#import "NSObject+HBCategory.h"
#import "NSString+HBCategory.h"
#import <objc/runtime.h>

@interface UITextFieldInputTypeManager : NSObject <UITextFieldDelegate>

@property (nonatomic, assign) UITextFieldInputType inputType;

@end

@implementation UITextFieldInputTypeManager

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (self.inputType == UITextFieldInputTypeNumber) {
        if ([string isEqualToString:@""] || [string isEqualToString:@"\n"]) {
            return YES;
        }
        
        return [NSString hb_validateNumber:string];
    }
    
    
    return YES;
}


@end

@interface UITextField ()

@property (nonatomic, strong) UITextFieldInputTypeManager *inputTypeManager;

@end

@implementation UITextField (HBTextLength)

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        SEL oldSEL = @selector(initWithFrame:);
        SEL newSEL = @selector(UITextField_HBCategory_initWithFrame:);
        [NSObject hb_swizzlingInstanceMethodWithClass:self originSel:oldSEL newSel:newSEL];
        
        [NSObject hb_swizzlingInstanceMethodWithClass:self originSel:@selector(removeFromSuperview) newSel:@selector(UITextField_HBCategory_removeFromSuperview)];
        
        [NSObject hb_swizzlingInstanceMethodWithClass:self originSel:@selector(setDelegate:) newSel:@selector(UITextField_HBCategory_setDelegate:)];
        
        [NSObject hb_swizzlingInstanceMethodWithClass:self originSel:NSSelectorFromString(@"dealloc") newSel:@selector(UITextField_HBCategory_dealloc)];
        
    });
}

- (instancetype)UITextField_HBCategory_initWithFrame:(CGRect)frame{
    
    if ([self UITextField_HBCategory_initWithFrame:frame]) {
        
        typeof(self) __weak weakSelf = self;
        [self addTarget:weakSelf action:@selector(UITextField_HBCategory_textChange_Edit) forControlEvents:UIControlEventEditingChanged];
    }
    return self;
}

- (void)UITextField_HBCategory_removeFromSuperview{
    [self UITextField_HBCategory_removeFromSuperview];
    NSLog(@"%s",__func__);
}

#pragma mark - property


- (void)setHb_inputType:(UITextFieldInputType)hb_inputType{
    objc_setAssociatedObject(self, @selector(hb_inputType), @(hb_inputType), OBJC_ASSOCIATION_ASSIGN);
    if (hb_inputType == UITextFieldInputTypeNumber) {
        self.inputTypeManager = [[UITextFieldInputTypeManager alloc] init];
        self.delegate = self.inputTypeManager;
    }
    if (self.inputTypeManager) {
        self.inputTypeManager.inputType = hb_inputType;
    }
    
}


- (UITextFieldInputType)hb_inputType{
    return [objc_getAssociatedObject(self, @selector(hb_inputType)) integerValue];
}



- (void)setHb_maxLength:(NSUInteger)hb_maxLength{
    objc_setAssociatedObject(self, @selector(hb_maxLength), @(hb_maxLength), OBJC_ASSOCIATION_ASSIGN);
}

- (NSUInteger)hb_maxLength{
    return [objc_getAssociatedObject(self, @selector(hb_maxLength)) unsignedIntegerValue];
}

- (void)setHb_textLengthChange:(UITextFieldTextLengthChange)hb_textLengthChange{
    objc_setAssociatedObject(self, @selector(hb_textLengthChange), hb_textLengthChange, OBJC_ASSOCIATION_COPY_NONATOMIC);
}


- (UITextFieldTextLengthChange)hb_textLengthChange{
    return objc_getAssociatedObject(self, @selector(hb_textLengthChange));
}


- (void)setInputTypeManager:(UITextFieldInputTypeManager *)inputTypeManager{
    objc_setAssociatedObject(self, @selector(inputTypeManager), inputTypeManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UITextFieldInputTypeManager *)inputTypeManager{
    return objc_getAssociatedObject(self, @selector(inputTypeManager));
}

- (void)UITextField_HBCategory_setDelegate:(id<UITextFieldDelegate>)delegate{
    if (self.hb_inputType == UITextFieldInputTypeNumber) {
        if (!self.inputTypeManager) {
            self.inputTypeManager = [[UITextFieldInputTypeManager alloc] init];
        }
        [self UITextField_HBCategory_setDelegate:self.inputTypeManager];
    }else{
        [self UITextField_HBCategory_setDelegate:delegate];
    }
}

- (void)UITextField_HBCategory_dealloc{
    NSLog(@"%s",__func__);
    [self UITextField_HBCategory_dealloc];
    
}

//- (void)setHb_showEndEditToolView:(BOOL)hb_showEndEditToolView{
//    objc_setAssociatedObject(self, @selector(hb_showEndEditToolView), @(hb_showEndEditToolView), OBJC_ASSOCIATION_ASSIGN);
//    if (hb_showEndEditToolView) {
//        <#statements#>
//    }
//}

#pragma mark - 公开方法

- (void)hb_showEndEditToolView{
    CGFloat height = 40;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, height)];
    view.backgroundColor = [UIColor whiteColor];
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    UIView *line= [UIView new];
    line.backgroundColor = [UIColor lightGrayColor];
    line.frame = CGRectMake(0, 0, screenWidth, 0.5);
    [view addSubview:line];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(resignFirstResponder) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"完成" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button setTitleColor:[UIColor colorWithRed:0 green:0 blue:0.8 alpha:1] forState:UIControlStateNormal];
    button.frame = CGRectMake(screenWidth - 64, 0, 64, height);
    [view addSubview:button];
    self.inputAccessoryView = view;
}

#pragma mark - 通知


- (void)UITextField_HBCategory_textChange_Edit{
    if (self.hb_maxLength <= 0) return;
    //预选编辑（高亮部分）
    UITextRange *textRange = self.markedTextRange;
    UITextPosition *position = [self positionFromPosition:textRange.start offset:0];
    //    NSLog(@"%@---%@",position, textRange);
    
    if (position && textRange) return;
    
    NSString *toBeString = self.text;
    //统计字符总长度（符號、字母、數字、漢字均算為1字元）
    NSRange range = NSMakeRange(0, 0);
    NSInteger textLength = 0;
    NSUInteger interceptTextMaxLength = 0;
    for (NSInteger idx = 0; idx < toBeString.length; ) {
        if (self.hb_maxLength > 0 && textLength <= self.hb_maxLength) {
            interceptTextMaxLength += range.length;
        }
        range = [toBeString rangeOfComposedCharacterSequenceAtIndex:idx];
        idx += range.length;
        textLength += range.length; //+=1
    }
    
    
    if (self.hb_maxLength > 0 && textLength > self.hb_maxLength && interceptTextMaxLength <= self.text.length) {
        self.text = [toBeString substringToIndex:interceptTextMaxLength];
//        textLength = self.hb_maxLength;
        textLength = self.text.length;
    }
    
    
    if (self.hb_textLengthChange) {
        self.hb_textLengthChange(textLength, self.hb_maxLength);
    }
}





@end
